<?php

namespace common\rest;

use Yii;
use yii\helpers\ArrayHelper;
use yii\data\ActiveDataProvider;

/**
 * DownloadAction implements the API endpoint for listing multiple models.
 *
 * For more details and usage information on IndexAction, see the [guide article on rest controllers](guide:rest-controllers).
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class DownloadAction extends \yii\rest\Action {

    const FORMAT_CSV = 'csv';
    const FORMAT_XLXS = 'xlxs';

    /**
     * @var string
     */
    public $format;

    /**
     * @return ActiveDataProvider
     */
    public function run() {
        if ($this->checkAccess) {
            call_user_func($this->checkAccess, $this->id);
        }
        return $this->prepareDataProvider();
    }

    /**
     * Prepares the data provider that should return the requested collection of the models.
     * @return ActiveDataProvider
     */
    protected function prepareDataProvider() {
        $requestParams = Yii::$app->getRequest()->getBodyParams();
        if (empty($requestParams)) {
            $requestParams = Yii::$app->getRequest()->getQueryParams();
        }
        if ($this->controller->hasProperty('storeId')) {
            $requestParams['store_id'] = $this->controller->storeId;
        }
        $format = ArrayHelper::getValue($requestParams, 'format', $this->format);
        $model = new $this->modelClass;
        $model->load($requestParams, '');
        if (stripos($format, static::FORMAT_CSV) !== false) {
            return $model->exportCsv();
        }
        ini_set('max_execution_time', 200);
        return $model->export();
    }

    /**
     * @param Action $action
     * @return bool whether the action should continue to be executed.
     */
    public function beforeAction($action) {
        if (!parent::beforeAction($action)) {
            return false;
        }
        $controller = $action->controller;
        $controller->exposeHeaders = ArrayHelper::merge($controller->exposeHeaders, [
            'Content-Disposition'
        ]);
        return true;
    }

}
